package com.framework.common.model.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JacksonStdImpl;
import com.fasterxml.jackson.databind.ser.std.NumberSerializer;
import java.io.IOException;

/**
 * @author 龘鵺
 * @className com.framework.common.model.jackson
 * @description 处理JS数值类，最大最小值转换为字符串。避免精度缺失
 * @datetime 2025-01-09 11:11:11
 * @version 1.0
 */
@JacksonStdImpl
public class BigNumberSerializer extends NumberSerializer {
    /**
     * 根据JS, Number.MAX_SAFE_INTEGER 与 Number.MIN_SAFE_INTEGER 得来
     */
    private static final long MAX_SAFE_INTEGER = 9007199254740991L;
    private static final long MIN_SAFE_INTEGER = -9007199254740991L;

    /**
     * @title 创建静态实例
     * @description 创建静态实例
     * @author 龘鵺
     * @datetime 2025-01-09 11:11:11
     */
    public static final BigNumberSerializer instance = new BigNumberSerializer(Number.class);

    public BigNumberSerializer(Class<? extends Number> rawType) {
        super(rawType);
    }

    /**
     * @param value    1 参数
     * @param g        2 json生成对象
     * @param provider 3 序列化对象
     * @title 超出范围 序列化位字符串
     * @description 超出范围 序列化位字符串
     * @author 龘鵺
     * @datetime 2025-01-09 11:11:11
     */
    @Override
    public void serialize(Number value, JsonGenerator g, SerializerProvider provider) throws IOException {
        if (value.longValue() > MIN_SAFE_INTEGER && value.longValue() < MAX_SAFE_INTEGER) {
            super.serialize(value, g, provider);
        } else {
            g.writeString(value.toString());
        }
    }
}
